/**
 * Author: Ruocaled
 * Date: 9/12/11
 * Time: 1:37 PM
 * Version: 0.22.99936
 */
var global_external_page;
var global_login_page;
var global_watching_page;
var global_subject_page;
var global_character_page;
var global_update_page;
var global_fav_page;
var global_calendar_page;
var global_default_img = 'http://bgm.tv/img/info_only_m.png';
var _d = (new Date()).getDay() - 1;
var _today = (_d === -1) ? 6 : _d;

$(document).live("mobileinit", function ()
{
    //overwrite default settings
    $.mobile.loadingMessage = '接收电波中...';
});

$(document).ready(function () {
    $('#welcome_btn').live('tap', goToLoginPage);
});

function LoginPage() {
    function onSubmit() {
        goToWatchingPage();
        return false;
    }
    this.id = '#login';
    this.initializePage = function () {
        this.resetPage();
        this.createBinding();
        this.changePage();
    };
    this.changePage = function () {
        //TODO:RESUABLE FUNCTION, NEED A COMMON PAGE OBJECT
        $.mobile.changePage(this.id, {
            transition: "slide"
        });
    };
    this.createBinding = function () {
        $('#login_form').die('submit');
        $('#login_form').live('submit', onSubmit);
    };
    this.resetPage = function () {
        var last_username = getCookie('th_username');
        $('#username').val('');
        $('#password').val('');
        if (last_username) {
            $('#username').val(last_username);
        }
    }
}

function CalendarPage() {
    var self = this;
    this.id = '#calendar';
    this.data = null;
    this.initializePage = function () {

        this.createBinding();
        this.postRequest();
    };
    this.postRequest = function () {
        postRequest("calendar.php", {
            ilove: "bgm"
        }, handleData);
    };
    this.createBinding = function () {
        $('.calendar_li a').die('tap');
        $('.calendar_li a').live('tap', goToSubjectPage);
    };

    this.changePage = function () {
        $.mobile.changePage(this.id, {
            transition: "slide"
        });
    };

    function handleData(data) {
        self.data = data;
        var x_len = data.length;
        for (var x = 0; x < x_len; x += 1) {
            var t = [];
            var i = 0;
            var y_len = data[x].items.length;
            t[i++] = '<li data-role="list-divider">';
            t[i++] = data[x].weekday.cn;
            t[i++] = '</li>';
            for (var y = 0; y < y_len; y += 1) {
                t[i++] = '<li' + ' class="calendar_li"';
                t[i++] = global_watching_page.checkIfWatching(data[x].items[y].id);
                t[i++] = '>';
                t[i++] = '<a data-ajax="false" href="javascript:void(0);" subject_id="';
                t[i++] = data[x].items[y].id;
                t[i++] = '">';
                t[i++] = '<span class="thumbnail"><span class="image"><img src="';
                t[i++] = data[x].items[y].images.medium;
                t[i++] = '"></span><span class="overlay"></span></span>';
                t[i++] = '<h1>';
                t[i++] = data[x].items[y].name_cn;
                t[i++] = '</h1>';

            }

            if (_today === x) {
                $('#calendar-list').append(t.join(''));
            } else if (x < _today) {
                $('#pre-list').append(t.join(''));
            } else {
                $('#post-list').append(t.join(''));
            }
        }

         self.changePage();
    }
}

function WatchingPage() {
    var self = this;
    this.id = '#watching';
    this.data = null;
    this.fake_data = '';
    this.initializePage = function () {
        this.resetPage();
        this.createBinding();
        this.postRequest();
    };
    this.postRequest = function () {
        postRequest("login.php", {
            username: $("#username").val(),
            password: $("#password").val()
        }, handleData);
    };
    this.resetPage = function () {
        if (getCookie('th_avatar') && getCookie('th_username'))
        {
            try
            {
                var t = [];
                var i = 0;
                t[i++] = '	<li data-role="list-divider">特别感谢</li><li><a href="http://bgm.tv/user/';
                t[i++] = getCookie('th_username');
                t[i++] = '"><img src="';
                t[i++] = getCookie('th_avatar');
                t[i++] = '" /><h4>+You</h4><span>一个好人</span></a></li>';
                $('#staff-list').append(t.join(''));
            }
            catch (err)
            {}
        }
    };
    this.createBinding = function () {
        $('.subject_li a').die('tap');
        $('.subject_li a').live('tap', goToSubjectPage);
        $('#calendar-btn').die('tap');
        $('#calendar-btn').live('tap',goToCalendarPage);
    };
    this.changePage = function () {
        $.mobile.changePage(this.id, {
            transition: "slide"
        });
    };

   this.checkIfWatching = function(id)
{
    var data_theme = "";
    var data = this.data;
    if (data && id)
    {
        for (var i = 0; i < data.length; i++)
        {
            if (id == data[i].subject.id)
            {
                data_theme = 'data-theme = "b"';
                break;
            }
        }
    }
    return data_theme;
}

    function handleData(data) {
        if (!data) {
            data = self.fake_data;
        }
        self.data = data;
        createWatchingPageWith(data);

        function createWatchingPageWith(data) {
            var t = [];
            var i = 0;
            var x_len = data.length;
            for (var x = 0; x < x_len; x += 1) {
                t[i++] = '<li' + ' class="subject_li">';
                t[i++] = '<a data-ajax="false" href="javascript:void(0);" subject_id="';
                t[i++] = data[x].subject.id;
                t[i++] = '">';
                t[i++] = '<span class="thumbnail"><span class="image"><img src="';
                t[i++] = data[x].subject.images.medium;
                t[i++] = '"></span><span class="overlay"></span></span>';
                t[i++] = '<h1>';
                t[i++] = data[x].subject.name_cn;
                t[i++] = '</h1>';
                t[i++] = '<p><span class="progress" style="width:';
                t[i++] = parseInt(data[x].ep_status) * 100 / parseInt(data[x].subject.eps);
                t[i++] = '%">';
                t[i++] = data[x].ep_status;
                t[i++] = '/';
                t[i++] = data[x].subject.eps;
                t[i++] = '</span></p>';
                t[i++] = '<p class="ui-li-aside"></p>';
                t[i++] = '</a>';
                t[i++] = '</li>';
            }
            $('#watching-list').html(t.join(''));
        }
        self.changePage();
    }
}

function SubjectPage(subject_id) {
    var self = this;
    this.subject_id = subject_id;
    this.id = "#subject";
    this.data = null;
    this.rating = 0;
    this.status = null;
    //TODO:this.comment = null;
    this.initializePage = function () {
        this.resetPage();
        this.createBinding();
        this.postRequest();
    };
    this.updatePage = function () {};
    this.resetPage = function () {
        try {
            $(this.id).page('destroy');
        } catch (e) {}
    };
    this.postRequest = function () {

        postRequest("subject.php", {
            subject_id: this.subject_id
        }, handleData);
    };
    this.createBinding = function () {
        $('.staff_li a').die('tap');
        $('.staff_li a').live('tap', goToBgmPrsnPage);
        $('.crt_li a').die('tap');
        $('.crt_li a').live('tap', goToCharacterPage);
        $('.status-btn').die('tap');
        $('.status-btn').live('tap', goToUpdatePage);
        $('.fav-btn').die('tap');
        $('.fav-btn').live('tap', goToFavPage);
    };
    this.changePage = function () {
        $.mobile.changePage(this.id, {
            transition: "slide"
        });
    };

    function goToBgmPrsnPage() {
        var id = $(this).attr('staff_id');
        if (id) {
            //http://bgm.tv/m/topic/crt/12347
            global_external_page = window.open("http://bgm.tv/m/topic/prsn/" + id, 'global_external_page')
            if (window.focus) {
                global_external_page.focus()
            }
        }
        return false;
    }

    function handleData(data) {
        if (!data) {
            data = self.fake_data;
        }
        self.data = data;
        var ep = data.ep;
        var progress = data.progress;
        var subject = data.subject;
        var collection = data.collection;
        createSubjectEpStatusWith(ep, progress, subject);
        createSubjectInfoWith(subject, collection);



        function createSubjectEpStatusWith(ep, progress, subject) {
            var t = [];
            var i = 0;
            var x_len = ep.eps.length;
            var y_len = (progress) ? progress.eps.length : 0;
            var did = false;
            var sort_len = ep.eps[ep.eps.length - 1].sort.toString().length;
            var status_id = 'NA';
            for (var x = 0; x < x_len; x += 1) {
                if (progress !== undefined) {
                    for (var y = 0; y < y_len; y += 1) {
                        if (ep.eps[x].id === progress.eps[y].id) {
                            did = true;
                            status_id = progress.eps[y].status.css_name;
                        }
                    }
                }
                t[i++] = '<a ep_id="';
                t[i++] = ep.eps[x].id;
                t[i++] = '" ep_sort="';
                t[i++] = ep.eps[x].sort;
                t[i++] = '" base-status="';
                t[i++] = ep.eps[x].status;
                t[i++] = '" class="';
                if (did !== true) {
                    t[i++] = ep.eps[x].status;
                } else {
                    t[i++] = status_id;
                }
                t[i++] = ' status-btn" href="#update" data-rel="dialog" data-transition="pop" data-inline="true" data-role="button" data-theme="a">';
                t[i++] = zeroFill(ep.eps[x].sort, sort_len);
                t[i++] = '</a>';
                did = false;
            }
            $('#progress-list').html(t.join(''));
            $('#subject > div > h1').html(ep.name_cn);
        }

        function createSubjectInfoWith(subject, collection) {
            self.rating = collection.rating;
            if (collection.status){
                self.status = collection.status.type ;
            }


            var crt = subject.crt;
            var staff = subject.staff;
            var t = [];
            var i = 0;
            creteSubjectBasicInfo();
            createCrtListWith(crt);
            createStaffListWith(staff);
            $('#subject-info').html(t.join(''));

            function creteSubjectBasicInfo() {
                t[i++] = '<div><dl><dt><h1>';
                t[i++] = subject.name;
                t[i++] = '<a href="#fav" ';
                t[i++] = 'data-rel="dialog" data-transition="pop" data-role="button" data-icon="star" data-iconpos="notext" class="fav-btn">收藏</a></h1>'
                t[i++] = '</dt><dd>';
                t[i++] = subject.summary;
                t[i++] = '</dd><br></div><div><ul data-role="listview" data-theme="g" id="info-list">';
            }

            function createCrtListWith(crt) {
                if (crt) {
                    var x_len = crt.length;
                    t[i++] = '<li data-role="list-divider">登场角色</li>';
                    for (var x = 0; x < x_len; x += 1) {
                        var crt_img = (crt[x].images) ? crt[x].images.grid : global_default_img;
                        t[i++] = '<li class="crt_li"><a crt_id="';
                        t[i++] = crt[x].id;
                        t[i++] = '" data-ajax="false" href="javascript:void(0);"><span class="thumbnail"><span class="image"><img src="';
                        t[i++] = crt_img;
                        t[i++] = '"></span><span class="overlay"></span></span><h3>';
                        t[i++] = crt[x].name;
                        t[i++] = '</h3><p>';
                        t[i++] = crt[x].role_name;
                        t[i++] = '</p></a></li>';
                    }
                }
            }

            function createStaffListWith(staff) {
                if (staff) {
                    t[i++] = '<li data-role="list-divider">制作人员</li>';
                    var s_len = staff.length;
                    for (var s = 0; s < s_len; s += 1) {
                        var staff_img = (staff[s].images) ? staff[s].images.grid : global_default_img;
                        t[i++] = '<li class="staff_li"><a staff_id="';
                        t[i++] = staff[s].id;
                        t[i++] = '" data-ajax="false" href="javascript:void(0);"><span class="thumbnail"><span class="image"><img src="';
                        t[i++] = staff_img;
                        t[i++] = '"></span><span class="overlay"></span></span><h3>';
                        t[i++] = staff[s].name;
                        t[i++] = '</h3><span class="ui-li-count ui-btn-up-c ui-btn-corner-all">';
                        t[i++] = (staff[s].comment) ? staff[s].comment : 0;
                        t[i++] = '</span><p>';
                        t[i++] = (staff[s].jobs) ? (staff[s].jobs).join('，') : '';
                        t[i++] = '</p></a></li>';
                    }
                }
                t[i++] = '</ul></div>';
            }
        }
        self.changePage();
    }
}

function CharacterPage(crt_id) {
    var self = this;
    this.id = "#character";
    this.crt_id = crt_id;
    this.data = null;
    this.fake_data = null;
    this.initializePage = function () {
        this.createBinding();
        this.postRequest();
    };
    this.resetPage = function () {
        try {
            $('#crt-info-list').listview('refresh');
        } catch (e) {}
    };
    this.changePage = function () {
        $.mobile.changePage(this.id, {
            transition: "slide"
        });
    };
    this.createBinding = function () {
        $('#crt_a').die('tap');
        $('#crt_a').live('tap', goToBgmCrtPage);
    };
    this.postRequest = function () {
        handleData(getCrtByID(this.crt_id));
    };

    function goToBgmCrtPage() {
        var id = $(this).attr('crt_id');
        if (id) {
            //http://bgm.tv/m/topic/crt/12347
            global_external_page = window.open("http://bgm.tv/m/topic/crt/" + id, 'global_external_page');
            if (window.focus) {
                global_external_page.focus()
            }
        }
        return false;
    }

    function getCrtByID(local_crt_id) {
        var target_crt = null;
        if (global_subject_page && global_subject_page.data.subject) {
            for (var cr = 0; cr < global_subject_page.data.subject.crt.length; cr++) {
                if (local_crt_id == global_subject_page.data.subject.crt[cr].id) {
                    target_crt = global_subject_page.data.subject.crt[cr];
                    break;
                }
            }
        }
        return target_crt;
    }

    function handleData(data) {
        if (!data) {
            data = self.fake_data;
        }
        var local_crt = data;
        var t = [];
        var i = 0;
        var crt_img = (local_crt.images) ? local_crt.images.medium : _default_img;
        t[i++] = '<li id="crt_main"><span id="crt_clip"><img src="';
        t[i++] = crt_img;
        t[i++] = '" /></span><h1 id="crt_basic" style="font-size:';
        t[i++] = (local_crt.name.length > 4) ? 1.3 : 2;
        t[i++] = 'em">'
        t[i++] = local_crt.name;
        t[i++] = '</h1>';
        t[i++] = '</li>';
        var crt_actor = local_crt.actors;
        if (crt_actor) {
            var x_len = local_crt.actors.length;
            t[i++] = '<li data-role="list-divider">声优</li>'
            for (var x = 0; x < x_len; x += 1) {
                var actor_img = (crt_actor[x].images) ? crt_actor[x].images.grid : _default_img;
                t[i++] = '<li' + ' class="actor_li" actor_id="';
                t[i++] = crt_actor[x].id;
                t[i++] = '" ' + '><span class="thumbnail"><span class="image"><img src="';
                t[i++] = actor_img;
                t[i++] = '"></span><span class="overlay"></span></span><h1>';
                t[i++] = crt_actor[x].name;
                t[i++] = '</h1></li>';
            }
            t[i++] = '<li data-role="list-divider">资料</li>';
            var power = parseInt(local_crt.comment * 2 + local_crt.collects / 4);
            t[i++] = '<li><h3>战斗力</h3><p>';
            t[i++] = '<span class="progress" style="width:';
            t[i++] = 5 + power;
            t[i++] = '%">';
            t[i++] = 5 + power * power * power;
            t[i++] = '<span>';
            t[i++] = '</p></li>';
            t[i++] = (local_crt.name_cn !== '') ? '<li><h3>中文名</h3><p>' + local_crt.name_cn + '</p></li>' : '';
            if (local_crt.info) {
                t[i++] = (local_crt.alias) ? '<li><h3>别名</h3><p>' + local_crt.alias.join('，') + '</p></li>' : '';
                t[i++] = (local_crt.info.birth !== undefined) ? '<li><h3>生日</h3><p>' + local_crt.info.birth + '</p></li>' : '';
                t[i++] = (local_crt.info.bloodtype !== undefined) ? '<li><h3>血型</h3><p>' + local_crt.info.bloodtype + '</p></li>' : '';
                t[i++] = (local_crt.info.bwh !== undefined) ? '<li><h3>三围</h3><p>' + local_crt.info.bwh + '</p></li>' : '';
                t[i++] = (local_crt.info.gender !== undefined) ? '<li><h3>性别</h3><p>' + local_crt.info.gender + '</p></li>' : '';
                t[i++] = (local_crt.info.height !== undefined) ? '<li><h3>身高</h3><p>' + local_crt.info.height + '</p></li>' : '';
                t[i++] = (local_crt.info.weight !== undefined) ? '<li><h3>体重</h3><p>' + local_crt.info.weight + '</p></li>' : '';
            }
            t[i++] = '<li data-theme="b"><a id="crt_a" crt_id="';
            t[i++] = local_crt.id;
            t[i++] = '" href="javascript:void(0);"><h3>参与讨论</h3><span class="ui-li-count ui-btn-up-c ui-btn-corner-all">' + local_crt.comment + '</span></a></li>'
            $('#crt-info-list').html(t.join(''));
        }
        self.resetPage();
        self.changePage();
    }
}

function UpdatePage(ep_id, ep_sort) {
    var self = this;
    this.ep_id = ep_id;
    this.ep_sort = ep_sort;
    this.initializePage = function () {
        this.resetPage();
        this.createBinding();
    };
    this.resetPage = function () {
        var ep = getEpInfoByID(ep_id);
        var name = ep ? ep.name : 'update_status';
        var comment = ep ? ep.comment : 0;
        var air_date = ep ? ep.airdate : '';
        $('#update_status_header').html('ep.' + ep_sort + " " + name);
        $('#air_date').html(air_date);
        $('.ep-comments-count').html(comment);
    };

    this.createBinding = function () {
        $('#update_watched').die('tap');
        $('#update_watched').live('tap', function () {
            doUpdate('watched')
        });
        $('#update_queue').die('tap');
        $('#update_queue').live('tap', function () {
            doUpdate('queue')
        });
        $('#update_remove').die('tap');
        $('#update_remove').live('tap', function () {
            doUpdate('remove')
        });
        $('#update_drop').die('tap');
        $('#update_drop').live('tap', function () {
            doUpdate('drop')
        });

        $('#update_comment').die('tap');
        $('#update_comment').live('tap', goToBgmEpPage);
    };

    function getEpInfoByID(ep_id) {
        var r;
        if (global_subject_page && global_subject_page.data) var x_len = global_subject_page.data.ep.eps.length;
        for (var x = 0; x < x_len; x += 1) {
            if (ep_id == global_subject_page.data.ep.eps[x].id) { //lazy check, ingore the type here; cuz I'm lazy
                r = global_subject_page.data.ep.eps[x];
                break;
            }
        }
        return r;
    }

    function goToBgmEpPage()
{
    var ep_id = self.ep_id;
    if (ep_id !== 0)
    {
        window.open("http://bgm.tv/m/topic/ep/" + ep_id);
    }
}

    function doUpdate(stat) {
        postRequest("update.php", {
            ep_id: self.ep_id,
            status: stat
        }, handleData);
    }

    function handleData(data) {
        var update_url = data['request'];
        var array = update_url.split('/');
        var q = array[4].split('?');
        var stat = q[0];
        if (stat === 'watched') {
            $('[ep_id="' + self.ep_id + '"]').removeClass('Queue Drop Air NA Unknown');
            $('[ep_id="' + self.ep_id + '"]').addClass('Watched');
        } else if (stat === 'remove') {
            $('[ep_id="' + self.ep_id + '"]').removeClass('Watched Queue Drop Unknown');
            var base_status = $('[ep_id="' + self.ep_id + '"]').attr('base-status');
            $('[ep_id="' + self.ep_id + '"]').addClass(base_status);
        } else if (stat === 'drop') {
            $('[ep_id="' + self.ep_id + '"]').removeClass('NA Queue Watched Air Unknown');
            $('[ep_id="' + self.ep_id + '"]').addClass('Drop');
        } else if (stat === 'queue') {
            $('[ep_id="' + self.ep_id + '"]').removeClass('Watched Drop Air NA Unknown');
            $('[ep_id="' + self.ep_id + '"]').addClass('Queue');
        }
        $('#update').dialog('close');
    }
}

function FavPage(subject_id, rating, status) {
    var self = this;
    this.subject_id = subject_id;
    this.rating = rating;
    this.status = status;
    this.initializePage = function () {

        $("input[type='radio']").attr("checked", false);
        var r = $("select#rating");
        r[0].selectedIndex = 0;

        if (status) {
            $('#' + status).attr('checked', true);
        }
        if (rating) {
            r[0].selectedIndex = rating;
        }


        $("input[type='radio']").checkboxradio("refresh");
        r.selectmenu("refresh");
        this.createBinding();

    };
    this.resetPage = function () {};
    this.postRequest = function () {
        postRequest("collection.php", {
            collect_status: $('input[name=collect_status]:checked').val(),
            rating: $('#rating').val() + '',
            subject_id: self.subject_id
        }, handleData);

    };
    this.createBinding = function () {
        $('#collect_form').die('submit');
        $('#collect_form').live('submit', onSubmit);
        $('#collect_cancel').die('tap');
        $('#collect_cancel').live('tap', onCancel);
    };

    function handleData(data) {
        if (data) {
            global_subject_page.rating = data.rating;
            if (data.status){
                global_subject_page.status = data.status.type || null;
            }

        }
        $.mobile.hidePageLoadingMsg();
        $('#fav').dialog('close');
    }

    function onSubmit() {

        self.postRequest();
        return false;
    }

    function onCancel ()
    {
        $('#fav').dialog('close');
        return false;
    }

}


//=============================================Functions==================================

function goToFavPage() {
    var subject_id = global_subject_page.subject_id;
    var rating = global_subject_page.rating;
    var status = global_subject_page.status;
    global_fav_page = new FavPage(subject_id, rating, status);
    global_fav_page.initializePage();
}

function goToUpdatePage() {
    var ep_id = $(this).attr('ep_id');
    var ep_sort = $(this).attr('ep_sort');
    global_update_page = new UpdatePage(ep_id, ep_sort);
    global_update_page.initializePage();
}

function goToCharacterPage() {
    var crt_id = $(this).attr('crt_id');
    global_character_page = new CharacterPage(crt_id);
    global_character_page.initializePage();
    return false;
}

function goToSubjectPage() {
    var subject_id = $(this).attr('subject_id');
    global_subject_page = new SubjectPage(subject_id);
    global_subject_page.initializePage();
    return false;
}

function goToLoginPage() {
    if (getCookie('th_auth')){
        goToWatchingPage();
    }
    else{
        global_login_page = new LoginPage();
        global_login_page.initializePage();
    }

    return false;
}

function goToWatchingPage() {
    if (!global_watching_page || !global_watching_page.data) {
        global_watching_page = new WatchingPage();
        global_watching_page.initializePage();
    } else {
        global_watching_page.changePage();
    }
    return false;
}

function goToCalendarPage() {
    if (!global_calendar_page || !global_calendar_page.data) {
        global_calendar_page = new CalendarPage();
        global_calendar_page.initializePage();
    } else {
        global_calendar_page.changePage();
    }
    return false;
}
//============================================Common====================================

function zeroFill(str, str_len) {
    str = str.toString();
    if (str.length < str_len && str) {
        for (var i = 0; i < str_len - str.length; i++) {
            str = '0' + str;
        }
    }
    return str;
}

function getCookie(c_name) {
    var i, x, y, z, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            z = decodeURIComponent(y);
            break;
        }
    }
    return z;
}

function log(msg) {
    if (console !== undefined) {
        console.log(msg);
    }
}

function postRequest(target, paras, callback) {
    $.mobile.showPageLoadingMsg();	
    var login_error = false;
	log(target);

	log(paras);
    $.post(target, paras, function (data) {
        if (data) {
            log('POST_DATA:');
            log(data);
            if (data.code == undefined || data.code == '200') {
                callback(data);
            } else {
                login_error = true;
            }
        } else {
            log('EMPTY_POST_DATA');
        }
    }, "json").success(

    function () {}).error(

    function () {
        log('error');
        log('ERROR_CONNECT');
        login_error = true;
    }).complete(function () {
        $.mobile.hidePageLoadingMsg();	    
        log('COMPLETE');
        if (login_error === true) {
            log('COMPETE_WITH_ERROR');
        }
    });
}